package com.tx.framework.util;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

@Slf4j
public class HttpUtil {

	public static String doGet(String url) {
		return doGet(url, null);
	}

	public static String doGet(String url, List<NameValuePair> params) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		try {
			HttpGet httpget = null;
			if (params != null) {
				String str = EntityUtils.toString(new UrlEncodedFormEntity(
						params, Consts.UTF_8));
				httpget = new HttpGet(url + "?" + str);
			} else {
				httpget = new HttpGet(url);
			}
			log.info("request url:" + httpget.getRequestLine().toString());
			response = httpclient.execute(httpget);
			return EntityUtils.toString(response.getEntity());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (httpclient != null) {
					httpclient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "";
	}

	public static String doPost(String url, String json) {
		String result = "";
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(10000)// 设置连接主机服务超时时间
					.setConnectionRequestTimeout(10000)// 设置连接请求超时时间
					.setSocketTimeout(30000)// 设置读取数据连接超时时间
					.build();
			httpPost.setConfig(requestConfig);
			httpPost.addHeader("content-type", "application/json;charset=utf-8");
			httpPost.setEntity(new StringEntity(json, Charset.forName("UTF-8")));
			CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
			result = EntityUtils.toString(httpResponse.getEntity());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String urlEncode(String param) {
		try {
			return URLEncoder.encode(param, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static void doGetQRImage(String url, String picURL) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		try {
			HttpGet httpget = new HttpGet(url);
			response = httpclient.execute(httpget);
			byte[] bytes = readInputStream(response.getEntity().getContent());
			if (bytes != null && bytes.length > 0) {
				buff2Image(bytes, picURL);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (httpclient != null) {
					httpclient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private static byte[] readInputStream(InputStream inputStream)
			throws IOException {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inputStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		return outStream.toByteArray();
	}

	public static void buff2Image(byte[] b, String picURL) throws Exception {
		FileOutputStream fout = new FileOutputStream(picURL);
		fout.write(b);
		fout.close();
	}

	/*
	 * public static String doPost(String url, String json) { String result =
	 * ""; try { CloseableHttpClient httpClient = HttpClients.createDefault();
	 * HttpPost httpPost = new HttpPost(url); log.info("request url:" +
	 * httpPost.getRequestLine().toString()); RequestConfig requestConfig =
	 * RequestConfig.custom() .setConnectTimeout(10000)// 设置连接主机服务超时时间
	 * .setConnectionRequestTimeout(10000)// 设置连接请求超时时间
	 * .setSocketTimeout(30000)// 设置读取数据连接超时时间 .build();
	 * httpPost.setConfig(requestConfig); httpPost.addHeader("content-type",
	 * "application/json;charset=utf-8"); httpPost.addHeader("Authorization",
	 * "Bearer " + Const.MUDU_TOKEN); if (!StringUtils.isEmpty(json)) {
	 * httpPost.setEntity(new StringEntity(json, Charset .forName("UTF-8"))); }
	 * CloseableHttpResponse httpResponse = httpClient.execute(httpPost); result
	 * = EntityUtils.toString(httpResponse.getEntity()); } catch (Exception e) {
	 * e.printStackTrace(); } return result; }
	 */

	public static String doPostAndParams(String url, String json,
			List<NameValuePair> params) {
		String result = "";
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			String str = EntityUtils.toString(new UrlEncodedFormEntity(params,
					Consts.UTF_8));
			HttpPost httpPost = new HttpPost(url + "?" + str);
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(10000)// 设置连接主机服务超时时间
					.setConnectionRequestTimeout(10000)// 设置连接请求超时时间
					.setSocketTimeout(30000)// 设置读取数据连接超时时间
					.build();
			httpPost.setConfig(requestConfig);
			httpPost.addHeader("content-type", "application/json;charset=utf-8");
			httpPost.setEntity(new StringEntity(json, Charset.forName("UTF-8")));
			CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
			result = EntityUtils.toString(httpResponse.getEntity());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
